#include "./parts.h"
#include "../../device/gpio.h"
#include "./sensor.h"

namespace driver {

using namespace device::gpio;
using namespace utils;

using JAW_CTRL = PC<12>;
using JAW_DIR = PC<13>;
using FILM = PC<10>; // 封膜机

Parts::Parts() {

    RCC->APB2ENR |= RCC_APB2ENR_IOPCEN;

    config_pp_out<JAW_CTRL, JAW_DIR>();
    config_pp_out<FILM>();
}

Error Parts::do_film() {
    if (!sensor->is_film_drop()) {
        return ec::ARM_FILM_NOT_CUP;
    }

    if (!sensor->is_film_cargo()) {
        return ec::ARM_FILM_STAUS_INVALID;
    }

    Error err;
    uint32_t time_count = 0;
    
    FILM::set();
    osDelay(500);
    FILM::clr();

    while (sensor->is_film_cargo() ) {
        osDelay(50);
        time_count += 50;
        if (time_count >= FILM_START_TIMEOUT) {
            err = ec::ARM_FILM_TIMEOUT;
            goto finish;
        }
    }

    time_count = 0;
    while (!sensor->is_film_cargo() ) {
        osDelay(50);
        time_count += 50;
        if (time_count >= FILM_TIMEOUT) {
            err = ec::ARM_FILM_TIMEOUT;
            goto finish;
        }
    }

finish:
    return err;
}

void Parts::jaw_open() {
    JAW_CTRL::set();
    JAW_DIR::set();
    osDelay(200);
}

void Parts::jaw_close() {
    JAW_CTRL::set();
    JAW_DIR::clr();
    osDelay(200);
}

void Parts::jaw_release() {
    JAW_CTRL::clr();
    JAW_DIR::clr();
}

}
